<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>模板</title>
    <style>
      .list {
        width: 200px;
        height: 210px;
        background-color: green;
        overflow: auto;
      }

      .news {
        border-bottom: 1px red solid;
        margin-left: 10px;
        height: 30px;
        width: 173px;
      }
    </style>
  </head>
  <body>
    <!-- 准备好一个容器 -->
    <div id="test"></div>

    <!-- 引入react核心库 -->
    <script
      type="text/javascript"
      src="../js/17.0.1/react.development.js"
    ></script>
    <!-- 引入react-dom，用于支持react操作DOM -->
    <script
      type="text/javascript"
      src="../js/17.0.1/react-dom.development.js"
    ></script>
    <!-- 引入babel，用于将jsx转换成js -->
    <script type="text/javascript" src="../js/17.0.1/babel.min.js"></script>
    <script type="text/babel">
      class NewsList extends React.Component {
        state = { newsArr: [] };

        componentDidMount() {
          setInterval(() => {
            //获取原来的状态
            const { newsArr } = this.state;
            //模拟一条新闻
            const news = "新闻" + (newsArr.length + 1);
            //更新状态
            this.setState({ newsArr: [news, ...newsArr] });
          }, 1000);
        }

        getSnapshotBeforeUpdate() {
          return this.refs.list1.scrollHeight;
        }

        componentDidUpdate(preProps, preState, height) {
          //scrollTop表示窗口距离顶端的距离，每次添加一条新闻，累计添加新高度-旧高度的差值
          this.refs.list1.scrollTop += this.refs.list1.scrollHeight - height;
        }

        render() {
          return (
            <div className="list" ref="list1">
              {this.state.newsArr.map((n) => {
                return <div className="news">{n}</div>;
              })}
            </div>
          );
        }
      }

      ReactDOM.render(<NewsList />, document.querySelector("#test"));
    </script>
  </body>
</html>
